package com.h3c.ptability.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.h3c.ptability.config.RfcManager;
import com.h3c.ptability.dto.BdPostDTO;
import com.h3c.ptability.dto.SapPostDTO;
import com.h3c.ptability.entity.BdPost;
import com.h3c.ptability.mapper.BdPostMapper;
import com.h3c.ptability.mapstruct.BdPostMapstruct;
import com.h3c.ptability.service.IBdPostService;
import com.h3c.ptability.vo.BdPostVO;
import com.sap.conn.jco.*;
import com.xxl.job.core.log.XxlJobLogger;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 岗位表(BdPost)表服务实现类
 *
 * @author makejava
 * @since 2022-06-24 17:45:07
 */
@Service
public class BdPostServiceImpl extends ServiceImpl<BdPostMapper, BdPost> implements IBdPostService {

    @Resource
    private RfcManager rfcManager;

    @Override
    public IPage<BdPostVO> searchBdPost(BdPostDTO post) {
        String postName = post.getPostName();
        String deptId = post.getDeptId();
        QueryWrapper<BdPost> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(deptId)) {
            queryWrapper.lambda().eq(BdPost::getDeptId, deptId);
        }
        if (StringUtils.isNotBlank(postName)) {
            queryWrapper.lambda().like(BdPost::getPostName, postName);
        }
        IPage<BdPost> page = page(new Page<>(1, 50), queryWrapper);
        IPage<BdPostVO> convert = page.convert(BdPostMapstruct.INSTANCE::dbToVO);
        convert.setTotal(page.getTotal());
        return convert;
    }

    @Override
    public IPage<BdPostVO> searchPost(SapPostDTO post) {
        String postName = post.getPostName();
        QueryWrapper<BdPost> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(postName)) {
            queryWrapper.lambda().like(BdPost::getPostName, postName);
        }
        IPage<BdPost> page = page(new Page<>(1, 50), queryWrapper);
        IPage<BdPostVO> convert = page.convert(BdPostMapstruct.INSTANCE::dbToVO);
        convert.setTotal(page.getTotal());
        return convert;
    }

    @Override
    public void syncPostJob() {
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
            Date date = new Date();
            String startDate = dateFormat.format(date);
            String endDate = dateFormat.format(DateUtils.addDays(date, 1));
            XxlJobLogger.log("查询数据时间间隔：{}-{}", startDate, endDate);

            rfcManager.connect();
            JCoDestination destination = rfcManager.getDestination();
            JCoFunction function = rfcManager.getFunction(destination, "ZRFC_GET_GWXX_NEW");//调用SAP接口
            JCoParameterList importParameter = function.getImportParameterList();
            importParameter.setValue("BEGDA", startDate);
            importParameter.setValue("ENDDA", endDate);
            function.execute(destination);

            XxlJobLogger.log("查询成功，开始获取数据");
            List<BdPost> list = new ArrayList<>();
            JCoParameterList exportParameterList = function.getTableParameterList();
            JCoTable table = exportParameterList.getTable("T_TABLE");
            int num = 0;
            while (table.nextRow()) {
                BdPost bdPost = new BdPost();
                bdPost.setPostId(table.getString("OBJID"));
                bdPost.setPostName(table.getString("STEXT_S"));
                bdPost.setPostText(table.getString("ZGWWB"));
                bdPost.setDeptId(table.getString("ORGEH"));
                bdPost.setDeptName(table.getString("STEXT_O"));
                bdPost.setPostBigCategory(table.getString("ZCLA1T"));
                bdPost.setPostMidCategory(table.getString("ZCLA2T"));
                bdPost.setSubPost(table.getString("ZCLA3T"));
                bdPost.setPostLevel(table.getString("PSLVL"));
                String opType = table.getString("ZBS");
                //I新增 M修改 D删除 N无变化
                if (!opType.equals("D")) {
                    list.add(bdPost);
                }
                num++;
            }
            XxlJobLogger.log("获取数据完毕，共获取{}条数据", num);
            XxlJobLogger.log("获取数据完毕，共保存{}条数据", list.size());
            saveOrUpdateBatch(list);
            XxlJobLogger.log("更新成功，开始删除");

            List<String> postIdList = list.stream().map(BdPost::getPostId).collect(Collectors.toList());
            QueryWrapper<BdPost> queryWrapper = new QueryWrapper<>();
            if (postIdList.isEmpty()) {
                XxlJobLogger.log("没有岗位数据，全部删除");
            } else {
                queryWrapper.lambda().notIn(BdPost::getPostId, postIdList);
            }
            int delNum = getBaseMapper().delete(queryWrapper);
            XxlJobLogger.log("共删除{}条数据", delNum);
        } catch (Exception e) {
            log.error("同步岗位失败：", e);
        }
    }
}

